<?php


namespace App\Http\Controllers\Alipay;


use App\Http\Controllers\Alipay\BaseVerifyController;
use App\Http\Controllers\Wechat\BaseController;
use App\Models\BankCard;
use App\Models\Help;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\ShopSms;
use App\Models\ShopUser;
use App\Services\AntchainService;
use App\Services\WechatService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\SmsService;
use App\Services\SuningPayService;
use Illuminate\Http\Request;
use App\Models\Bank;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\OtherWithholdLog;
use App\Models\YifubaoPay;

class BankSuningController extends BaseController
{

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->request = $request;
        $this->uid = $this->member['id'];
    }

    /**
     * 获取服务协议
     */
    public function getYiFuBaoAgree(){
        $agreement = Help::where('id',52)->select('name','content')->first();
        $agreement = obToArray($agreement);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $agreement);
    }
    /**
     * 银行名称列表
     * @return false|string
     */
    public function bankList(){
        $Bank=new Bank();
        $banklist=$Bank->getAll();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功',$banklist);
    }

    /**
     * 已签约银行卡
     * @return false|string
     */
    public function myBankCard(){
        $Bank=new BankCard();
        $banklist=$Bank->getMemberAll($this->uid);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功',$banklist);
    }

    /**
     * 协议支付签约申请接口
     * @param Request $request
     * @return false|string
     */
    public function readySign(){
        $request=$this->request->post();
        $bank=Bank::detail($request['bank_id']);
        if(!$bank){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '所选银行不存在');
        }

        $validator = Validator::make($request, [
            'cardNo' => 'required',
            'mobileNo' => 'required',
            'bank_id' => 'required',
        ]);
        if ($validator->fails()) return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请完善信息');

        if(!$this->member['cert_name']||!$this->member['cert_no']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请先进行实名认证');
        }

        $bank_info['card_holder_name']=$this->member['cert_name'];
        $bank_info['cert_no']=$this->member['cert_no'];//持卡人身份证号码
        $bank_info['mobile_no']=$request['mobileNo'];//mobileNo
        $bank_info['card_no']=$request['cardNo'];//银行卡
        $bank_info['bank_code']=$bank['bank_code'];
        $bank_info['uid'] = $this->uid.'sn';

        $res=SuningPayService::agreementPaymentSign($bank_info);//银行卡协议支付
        if($res['statusCode']!='S'){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['responseMsg']);
        }

        $bank_info['bank_id'] = $bank['id'];
        $bank_info['bank_name'] = $bank['bank_name'];
        $bank_info['msgId'] = $res['data']['msgId'];
        $result = (new BankCard)->create($bank_info);
        if($result){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取验证码成功',$bank_info['msgId']);
        }
    }

    /**
     * 协议支付签约确认接口
     */
    public function confirmSigning(Request $request){
        $data['msgId']=$request['msgId'];
        $data['verificationCode']=$request['verificationCode'];
        $res=SuningPayService::agreementPayGatewayConfirm($data);//银行卡协议支付
        if($res['statusCode']!='S'){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['responseMsg']);
        }
        $result=BankCard::where('msgId',$data['msgId'])->update(['contract_no'=>$res['data']['contractNo']]);
        if($result){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '签约成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '签约失败，请重新提交');
        }
    }

    /**
     * 协议支付签约确认接口
     */
    public function confirmPay(Request $request){

       try {
            $orderId = $request->input('orderId','');
            $leaseId = $request->input('leaseId','');
            $code= $request->input('code','');

            if(!$orderId || !$leaseId){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
           if($request['pay_type']!='wxpay') {
               $bank = BankCard::detail($request['unique_code2']);
               if (!$bank) {
                   return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该银行卡已失效');
               }

               $result = SmsService::checkCode($bank['mobile_no'], $code);
               if (!$result) {
                   return ReturnMsg(CommonService::HTTP_CODE_FAIL, '验证码输入有误');
               }
           }
        $order = Order::from('sp_order_2 as o')->where('o.id',$orderId)
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->select('o.id','o.uid','m.user_id','o.flow_id','o.pact_url','o.sign_status','o.status','o.id','o.seller_id','o.realname',
                'o.trade_no','o.mobile','o.other_order_id','o.other_user_id','o.rent_total','og.goods_title',
                'og.imgurl','o.is_skip','m.cert_name','m.cert_no','m.mobile','og.pact_type','o.month_total','o.is_renewal','o.parent_order_no')->first();

        $order = obToArray($order);
            if (!$order){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'待支付订单不存在');
            }
            if ($order['status']<10&&($order['sign_status']!=2||empty($order['pact_url']))){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请确认签约合同后再进行支付');
            }
            if(!$leaseId || !is_array($leaseId)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'租期格式错误');
            }
            $lease = OrderLease::where(['order_id'=>$orderId])->whereIn("id",$leaseId)->select('which_period','rent','paid_rent','status','overdue_days','overdue_amount')->get();
            $lease = obToArray($lease);
            if (!$lease){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账单不存在');
            }
            $totalRent = 0;
            $leaseNum = [];
            foreach ($lease as $item){
                //判断租期状态
                if(!in_array($item['status'],[OrderLease::ORDER_LEASE_STATUS_NOPAY,OrderLease::ORDER_LEASE_STATUS_REFUNDED,OrderLease::ORDER_LEASE_STATUS_OVERDUE])){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'租期包含不可支付账单');
                }
                $totalRent+=bcsub($item['rent']+$item['overdue_amount'],$item['paid_rent'],2);
                $leaseNum[] = $item['which_period'];
            }

           if($request['pay_type']=='wxpay'){
               $order['total_fee'] = sprintf('%.2f',$totalRent);
               $result=WechatService::pay($this->member['openId'],$order,$leaseId);
               $result['tradeNo'] = $order['trade_no'];
               $result['id'] = $order['id'];
               return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,$result['return_msg'],$result);
           }

            $shopName = ShopUser::where(['member_id'=>$order['seller_id']])->value('shopname');


            $data['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_PAY;
            $data['contractNo']=$bank['contract_no'];//'202307267881357'
            $data['goodsName']='主动支付'.$order['goods_title'].'|'.$shopName;
            $data['orderAmount']=sprintf('%.2f',$totalRent);
            $data['orderName']=base64_encode('主动支付第'.implode(',',$leaseNum).'期');
            $data['outOrderNo']=$order['id'].rand(1000,9999).time();
            $result=SuningPayService::agreementPaymentPay($data);//银行卡协议支付
            if($result['statusCode']=='S'){
                                //添加记录
                $insertData = [
                    'trans_id'=>$data['outOrderNo'],
                    'order_id'=>$order['id'],
                    'trade_no'=>$order['trade_no'],
                    'lease_id'=>implode(',',$leaseId),
                    'which_period'=>implode(',',$leaseNum),
                    'txn_amt'=>$data['orderAmount'],
                    'create_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s'),
                    'is_pay'=>YifubaoPay::PAY_YES
                ];
                YifubaoPay::insert($insertData);

                $leaseSave['trade_no']     = $order['trade_no'];
                $leaseSave['out_order_no'] = $data['outOrderNo'];
                $leaseSave['pay_time']  = time();
                $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                $leaseSave['pay_type'] = OrderLease::PAY_TYPE_YIFUBAO;

                //更改已还租期
                Order::where(['id' => $order['id']])->increment('month_paid',count($leaseId));

                $orderLease = OrderLease::whereIn('id',$leaseId)->select('id','which_period','rent')->get();
                $orderLease = obToArray($orderLease);
                $leaseTotal = [];
                $zlbLeaseId = [];
                foreach ($orderLease as $lease){
                    //更新账单数据
                    OrderLease::where('id',$lease['id'])->update($leaseSave);
                    if($lease['which_period'] == 1){
                        if($order['is_renewal'] == Order::ORDER_NOT_RENEWAL){
                            if($order['is_skip'] == Order::RISK_SKIP_YES){
                                $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                            }else{
                                $risk_res = ChargeService::RiskCreditUse($order['seller_id'],$order['id'],$order['cert_name'],$order['cert_no'],$order['mobile'],1);
                                $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                            }
                            $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                            Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                        }else{//续租订单不发货，第一期扣款成功订单状态直接变为租用中
                            if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                                $arr['status'] = OrderService::ORDER_STATUS_TOBE_RETURNED;
                            }else{
                                $arr['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;
                            }
                        }
                        Order::where(['id' => $order['id']])->update($arr);
                        //短信通知
                        ShopSms::orderPlaceSendToShop($order['seller_id'],$order['realname'],$order['trade_no']);
                        ShopSms::orderPaidSendToUser($order['seller_id'],$order['realname'],$order['trade_no'],$lease['rent'],$order['mobile'],$order['id']);
                    }else{
                        $zlbLeaseId[] = $lease['id'];
                        if($order['pact_type'] != GoodsService::GOODS_PACT_TYPE_GIVE){
                            //所有租期已全部支付，状态改为待归还
                            if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                                Order::where(['id' => $order['id']])->update(['status'=>OrderService::ORDER_STATUS_TOBE_RETURNED]);
                            }
                        }
                    }

                    OtherWithholdLog::orderWithholdLog($order['trade_no'],$lease['id'],$data['outOrderNo'],$order['trade_no'],$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,true,1);
                    $leaseTotal[$lease['id']] = $lease['rent'];

                    //关支付宝代扣
                    if($lease['which_period']>0&&$order['user_id']){
                        $lease_res = AntchainService::payRule($order['flow_id']);
                        if($lease_res['status']&&isset($lease_res['data'])&&!empty($lease_res['data'])){
                            $lease_data=json_decode($lease_res['data'],true);
                            $cancel_out_order_no=$lease_data['payRules'][$lease['which_period']-1]['outTradeNo'];
                            AntchainService::paysingletradeCancel($order['flow_id'],$cancel_out_order_no);
                        }
                    }
                }
                //更新实付款金额
                if($leaseTotal = computeDiscount($leaseTotal,$data['orderAmount'])){
                    foreach ($leaseTotal as $k=>$value){
                        //更新账单数据-商家实际收金额
                        OrderLease::where(["id"=>$k])->update(['paid_rent'=>$value]);
                    }
                }
                //检测逾期订单状态
                if($status = Order::checkOrderOverdueStatus($order['id'])){
                    Order::where(['id' => $order['id']])->update(['status'=>$status]);
                }




                $returnData['tradeNo'] = $data['outOrderNo'];
                $returnData['id'] = $order['id'];
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,$result['responseMsg'],$returnData);
            }else{

                $orderLease = OrderLease::whereIn('id',$leaseId)->select('id','which_period','rent')->get();
                foreach ($orderLease as $order_lease){
                    OtherWithholdLog::orderWithholdLog($order['trade_no'],$order_lease['id'],'','',$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,false,1);
                }

                return ReturnMsg(CommonService::HTTP_CODE_FAIL,$result['responseMsg']);
            }
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'支付失败');
        }



    }

    public function readyPay(Request $request){
        $bank=BankCard::detail($request['unique_code2']);
        if(!$bank){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该银行卡已失效');
        }
        $result=SmsService::sendCode($bank['mobile_no']);
        if($result){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '验证码发送成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '验证码发送失败');
        }
    }
    /**
     * 协议支付签约查询接口
     */
    public function querySign(Request $request){

        return SuningPayService::querySignAgreements();//银行卡协议支付
    }

}

